package com.glela.platform.service.impl;

import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.glela.api.aliyun.IdcardAPI;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseConstants;
import com.glela.common.util.DateUtil;
import com.glela.platform.mapper.UserIdCardMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.UserIdCard;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserIdCardService;

/**
 * @author gwq
 */
@Service("userIdCardService")
public class UserIdCardServiceImpl implements UserIdCardService {
	private static Logger logger = LoggerFactory.getLogger(UserIdCardServiceImpl.class);
	@Autowired
	private UserIdCardMapper userIdCardMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;

	public UserIdCard checkIdcard(String cardno, String name, Long userID) {
		// 获取验证次数
		int time = 3;
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("idcardTimes");
		if (baseRestrictions != null && baseRestrictions.getStatus() == 1) {
			time = baseRestrictions.getRestrictions();
		}
		// 校验数据
		UserIdCard userIdCard;
		cardno = StringUtils.deleteWhitespace(cardno);
		name = StringUtils.deleteWhitespace(name);
		if (IdcardTimes(userID) == 0) {// 验证次数用完
			return new UserIdCard(0, "目前小铺平台用户每人每天可进行" + time + "次实名验证，超过" + time + "次将不可再验证哦");
		}
		if (StringUtils.isAnyBlank(cardno, name) || userID == null) {// 其中一个为空
			return new UserIdCard(0, "海关数据库里搜索不到你的身份证号，可尝试使用亲友的身份证下单购买");
		}
		redisUtil.incr(RedisKeys.USER_IDCARDS + DateUtil.currentYourDate(BaseConstants.DATE_FORMAT_YYYYMMDD) + ":" + userID);// 验证次数加一
		userIdCard = userIdCardMapper.selectUserIdCardByIdCard(cardno);
		if (userIdCard != null) {// 已存储数据
			if (StringUtils.compare(userIdCard.getRealName(), name) == 0) {
				userIdCard.CodeAndMessage(1, "匹配成功");
			} else {
				userIdCard.CodeAndMessage(0, "保税区海关政策要求，身份证姓名与身份证号码须一致，请重试");
			}
		} else {
			// 请求第三方
			userIdCard = new UserIdCard();
			redisUtil.incr(RedisKeys.USER_IDCARDS + "sum");// 验证次数加一
			String idcadrJson = IdcardAPI.lianzhuoIdcard(cardno, name);
			if (StringUtils.isBlank(idcadrJson)) {// 格式不对
				userIdCard.CodeAndMessage(0, "海关数据库里搜索不到你的身份证号，可尝试使用亲友的身份证下单购买");
			} else if (StringUtils.equals("error", idcadrJson)) {
				userIdCard.CodeAndMessage(0, "海关数据库里搜索不到你的身份证号，可尝试使用亲友的身份证下单购买");
			} else {// 解析数据
				Boolean flag = ToUserIdCardBean(userIdCard, idcadrJson);
				if (flag) {
					userIdCard.setRealName(name);
					userIdCard.setCardNo(cardno);
					userIdCardMapper.insert(userIdCard);
				}
			}
		}
		return userIdCard;
	}

	public int IdcardTimes(Long userID) {
		try {
			String times = redisUtil.get(RedisKeys.USER_IDCARDS + DateUtil.currentYourDate(BaseConstants.DATE_FORMAT_YYYYMMDD) + ":" + userID + "");
			int time = 3;
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("idcardTimes");
			if (baseRestrictions != null && baseRestrictions.getStatus() == 1) {
				time = baseRestrictions.getRestrictions();
			}
			if (StringUtils.isBlank(times)) {
				return time;
			} else {
				int temp = Integer.parseInt(times);
				return temp >= time ? 0 : (time - temp);
			}
		} catch (Exception e) {
			logger.error("IdcardTimes error:{}", e.getMessage());
			return 0;
		}
	}

	public UserIdCard selectIDcard(Long userID, String name) {
		return null;
	}

	/** 数据解析 */
	private boolean ToUserIdCardBean(UserIdCard userIdCard, String json) {
		try {
			Map NumberJson = JSONObject.parseObject(json, Map.class);
			Map resp = JSONObject.parseObject(NumberJson.get("resp").toString(), Map.class);
			if ("0".equals(resp.get("code").toString())) {// 通过
				Map data = JSONObject.parseObject(NumberJson.get("data").toString(), Map.class);
				userIdCard.setSex(data.get("sex").toString());
				userIdCard.setAddress(data.get("address").toString());
				userIdCard.setBirthday(DateUtil.parse(data.get("birthday").toString(), "yyyy-MM-dd"));
				userIdCard.CodeAndMessage(1, resp.get("desc").toString());
				userIdCard.setIdcardJson(json);
				return true;
			} else {
				userIdCard.CodeAndMessage(0, "保税区海关政策要求，身份证姓名与身份证号码须一致，请重试");
				return false;
			}
		} catch (Exception e) {
			logger.error("ToUserIdCardBean 解析错误：{}", e.getMessage());
			return false;
		}
	}
}